package com.qhgrain.app.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.paas.base.modules.utils.lang.StringUtil;
import com.paas.base.modules.utils.page.PageBean;
import com.qhgrain.app.constant.SyncDataTypeEnum;
import com.qhgrain.app.constant.UrlEnum;
import com.qhgrain.app.syncto4Ainfo.SynclogAppInfo;
import com.qhgrain.app.syncto4Ainfo.SynclogRoleInfo;
import com.qhgrain.app.syncto4Ainfo.SynclogUnitInfo;
import com.qhgrain.app.syncto4Ainfo.SynclogUserInfo;
import com.qhgrain.app.util.ConfigUtil;
import com.qhgrain.app.vo.RoleVo;
import com.qhgrain.app.vo.SynclogVo;
import com.qhgrain.app.vo.User;
import com.qhgrain.gway.util.HttpUtil;
import com.sun.xml.fastinfoset.util.StringArray;

@Service
public class SyncTo4AService {
	private static Logger LOG = LoggerFactory.getLogger(SyncTo4AService.class);

	private static final String Base_Url = ConfigUtil.getProperties(UrlEnum.IAM);
	
	private static final String Role_Base_Url = Base_Url + "/iam/v1/groups";
	private static final String App_Base_Url = Base_Url + "/iam/v1/apps";
	private static final String User_Base_Url = Base_Url + "/iam/v1/users";
	private static final String Unit_Base_Url = Base_Url + "/iam/v1/depts";
	
	@Autowired
	private SynclogService synclogService;
	
	public void updateSynclog(String synclogId, String syncResult){
		
	}
	//角色（群组）
	public void syncAddRole(String roleId, String roleName, String roleCode, String roleType){
		
		Map<String,Object> paramMap = new HashMap<String,Object>();
		JSONObject paramJson = new JSONObject();
		paramJson.put("uuid", roleId);
		paramJson.put("name", roleName);
		paramJson.put("groupCode", roleCode);
		paramJson.put("groupType", roleType);//需确认类型的代表字符
		
		paramMap.put("groupJson", paramJson);
		
		System.out.println("同步新建群组:"+paramMap);
		
		String objInfo = paramMap.get("groupJson").toString();
		
			this.synclogService.addSynclog(roleId,roleName,SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "add", objInfo, "success");
		/*String syncResult;
		try {
			syncResult = HttpUtil.post(Role_Base_Url+"/createGroup", paramMap);
			JSONObject resJson = JSONObject.parseObject(syncResult);
			if("1".equals(resJson.getString("result"))){
				this.synclogService.addSynclog(roleId,roleName, SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "add", paramMap.toString(), "success");
			}else{
				this.synclogService.addSynclog(roleId,roleName,SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "add", syncResult, "fail");
			}
		} catch (IOException e) {
			this.synclogService.addSynclog(roleId,roleName,SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "add", e.getMessage(), "fail");
			LOG.error(e.getMessage());
		}*/
		
	}
	
	
	public void syncDelRole(List<RoleVo> roles){
		if(0 < roles.size()){
			for(RoleVo role : roles){
				String url = Role_Base_Url + "/deleteGroupByUuid/" +role.getId();
				try {
					String result = HttpUtil.delete(url);
					JSONObject resJson = JSONObject.parseObject(result);
					//4A删除成功
					if("1".equals(resJson.getString("result"))){
						this.synclogService.addSynclog(role.getId(),role.getName(), SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "delete", result, "success");
					}else{
						this.synclogService.addSynclog(role.getId(),role.getName(), SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "delete", resJson.getString("message")+"uuid:"+role.getId(), "fail");
					}
				} catch (Exception e) {
					LOG.error("删除角色同步到4A失败：" + e.getMessage());
					this.synclogService.addSynclog(role.getId(),role.getName(), SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "delete", e.getMessage()+"uuid:"+role.getId(), "fail");
				}
			}
			
		}
	}
	
	public void syncUpdateRole(String roleId, String roleName, String roleCode, String roleType){
		Map<String,String> paramMap = new HashMap<String,String>();
		JSONObject paramJson = new JSONObject();
		paramMap.put("uuid", roleId);
		//paramJson.put("uuid", roleId);
		paramJson.put("name", roleName);
		paramJson.put("groupCode", roleCode);
		paramJson.put("groupType", roleType);
		
		paramMap.put("groupJson", paramJson.toJSONString());
		
		String url = Base_Url + "/updateGroupByUuid/" + roleId;
		try {
			//this.synclogService.addSynclog(roleId,roleName, SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "update", "未同步更新角色", "success");
			String result = HttpUtil.put(url, paramMap);
			JSONObject resJson = JSONObject.parseObject(result);
			if("1".equals(resJson.getString("result"))){
				this.synclogService.addSynclog(roleId,roleName, SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "update", resJson.getString("data"), "success");
			}else{
				this.synclogService.addSynclog(roleId,roleName, SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "update", (String)paramMap.get("groupJson"), "fail");
			}
		} catch (Exception e) {
			this.synclogService.addSynclog(roleId,roleName, SyncDataTypeEnum.SyncDataType_AppGroup.getCode(), "update", e.getMessage(), "fail");
			LOG.error("同步更新角色到4A失败："+ e.getMessage());
		}
	}
	
	//应用
	public void syncAddApp(String appId,String appName,String businessType,String appUrl,
			String iconClass,String appCode,String appOrder,String description){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		JSONObject paramJson = new JSONObject();
		
		paramJson.put("uuid", appId);
		paramJson.put("name", appName);
		paramJson.put("type", businessType);
		paramJson.put("待确认url", appUrl);
		paramJson.put("待确认icon", iconClass);
		paramJson.put("待确认code", appCode);
		paramJson.put("displayOrder", appOrder);
		paramJson.put("description", description);
		
		paramMap.put("appJson", paramJson.toJSONString());
		
		String objInfo = paramMap.get("appJson").toString();
		this.synclogService.addSynclog(appId,appName,SyncDataTypeEnum.SyncDataType_App.getCode(), "add", objInfo, "success");
		
		/*
		String syncResult = HttpUtil.post(App_Base_Url+"/createApp", paramMap);
		JSONObject resJson = JSONObject.parseObject(syncResult);
		if("1".equals(resJson.getString("result"))){
			this.synclogService.addSynclog(appId,appName, SyncDataTypeEnum.SyncDataType_App.getCode(), "add", paramMap.toString(), "success");
		}else{
			this.synclogService.addSynclog(appId,appName,SyncDataTypeEnum.SyncDataType_App.getCode(), "add", paramMap.toString(), "fail");
		}*/
		
	}
	
	public void syncDelApp(String appIds){
		if(StringUtil.isNotBlank(appIds)){
			String[] appIdArray = appIds.split(",");
			for(String appId : appIdArray){
				String url = Role_Base_Url + "/deleteAppByUuid/" +appId;
				try {
					String result = HttpUtil.delete(url);
					JSONObject resJson = JSONObject.parseObject(result);
					//4A删除成功
					if("1".equals(resJson.getString("result"))){
						this.synclogService.addSynclog(appId,"", SyncDataTypeEnum.SyncDataType_App.getCode(), "delete", resJson.getString("data"), "success");
					}else{
						this.synclogService.addSynclog(appId,"", SyncDataTypeEnum.SyncDataType_App.getCode(), "delete", resJson.getString("message")+"uuid:"+appId, "fail");
					}
				} catch (Exception e) {
					LOG.error("删除角色同步到4A失败：" + e.getMessage());
					this.synclogService.addSynclog(appId,"", SyncDataTypeEnum.SyncDataType_App.getCode(), "delete", e.getMessage(), "fail");
				}
			}
			
		}
	}
	
	public void syncUpdateApp(String appId,String appName,String businessType,String appUrl,
			String iconClass,String appCode,String appOrder,String description){
		
		Map<String,Object> paramMap = new HashMap<String,Object>();
		JSONObject paramJson = new JSONObject();
		
		paramJson.put("uuid", appId);
		paramJson.put("name", appName);
		paramJson.put("type", businessType);
		paramJson.put("待确认url", appUrl);
		paramJson.put("待确认icon", iconClass);
		paramJson.put("待确认code", appCode);
		paramJson.put("displayOrder", appOrder);
		paramJson.put("description", description);
		
		paramMap.put("appJson", paramJson.toJSONString());
		
		String objInfo = paramMap.get("appJson").toString();
		
		System.out.println("更新应用到4A:"+paramJson.toJSONString());
		this.synclogService.addSynclog(appId,appName,SyncDataTypeEnum.SyncDataType_App.getCode(), "update", objInfo, "success");
		
		/*
		String syncResult = HttpUtil.put(App_Base_Url+"/updateAppByUuid/"+appId, paramMap);
		JSONObject resJson = JSONObject.parseObject(syncResult);
		if("1".equals(resJson.getString("result"))){
			this.synclogService.addSynclog(appId,appName, SyncDataTypeEnum.SyncDataType_App.getCode(), "update", paramMap.toString(), "success");
		}else{
			this.synclogService.addSynclog(appId,appName,SyncDataTypeEnum.SyncDataType_App.getCode(), "update", paramMap.toString(), "fail");
		}*/
		
	}
	
	//用户
	public void syncAddUser(User user){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		JSONObject paramJson = new JSONObject();
		
		
		
		//写成功日志
		this.synclogService.addSynclog(user.getUserId(), user.getUserName(), SyncDataTypeEnum.SyncDataType_User.getCode(), "add", "待定", "success");
		
	}
	
	public void syncDelUser(String loginNames){
		if(StringUtil.isNotBlank(loginNames)){
			String[] loginNameArray = loginNames.split(",");
			
			for(String loginName : loginNameArray){
				String url = Role_Base_Url + "/" +loginName;
				try {
					String result = HttpUtil.delete(url);
					JSONObject resJson = JSONObject.parseObject(result);
					//4A删除成功
					if("1".equals(resJson.getString("result"))){
						//数据ID存放用户登录名
						this.synclogService.addSynclog(loginName,"", SyncDataTypeEnum.SyncDataType_User.getCode(), "delete", resJson.getString("data"), "success");
					}else{
						this.synclogService.addSynclog(loginName,"", SyncDataTypeEnum.SyncDataType_User.getCode(), "delete", resJson.getString("message")+"loginName:"+loginName, "fail");
					}
				} catch (Exception e) {
					LOG.error("删除用户同步到4A失败：" + e.getMessage());
				}
			}
			
		}
	}
	
	public void syncUpdateUser(User user){
		Map<String,Object> paramMap = new HashMap<String,Object>();
		JSONObject paramJson = new JSONObject();
		
		
		
		//写成功日志
		this.synclogService.addSynclog(user.getUserId(), user.getUserName(), SyncDataTypeEnum.SyncDataType_User.getCode(), "update", "待定", "success");
		
	}
	
	//机构
	public void syncAddUnit(){
		
	}
	
	public void syncDelUnit(String unitIds){
		
		if(StringUtil.isNotBlank(unitIds)){
			String[] unitIdArray = unitIds.split(",");
			for(String unitId : unitIdArray){
				String url = Role_Base_Url + "/deleteGroupByUuid/" +unitId;
				try {
					String result = HttpUtil.delete(url);
					JSONObject resJson = JSONObject.parseObject(result);
					//4A删除成功
					if("1".equals(resJson.getString("result"))){
						this.synclogService.addSynclog(unitId,"", SyncDataTypeEnum.SyncDataType_Unit.getCode(), "delete", resJson.getString("data"), "success");
					}else{
						this.synclogService.addSynclog(unitId,"", SyncDataTypeEnum.SyncDataType_Unit.getCode(), "delete", resJson.getString("message")+"uuid:"+unitId, "fail");
					}
				} catch (Exception e) {
					LOG.error("删除机构同步到4A失败：" + e.getMessage());
				}
			}
			
		}
	}
	
	public void syncUpdataUnit(){
		
	}
	
	public void resyncFailData(List<SynclogRoleInfo> syncRoles,List<SynclogAppInfo> syncApps,List<SynclogUserInfo> syncUsers,List<SynclogUnitInfo> syncUnits){
		if(0 < syncRoles.size()){
			resyncFailRole(syncRoles);
		}
		
	}
	
	private void resyncFailRole(List<SynclogRoleInfo> roleList){
		
		for(SynclogRoleInfo syncRole : roleList){
			if("add".equals(syncRole.getSyncOpertaionType())){
				//syncAddRole(syncRole.getRoleId(), syncRole.getRoleName(), syncRole.getRoleRoleCode(), syncRole.getRoleType());
				LOG.info("重新同步新增role到4A,日志id:"+syncRole.getSyncSynclogId());
			
			
			
			}else if("delete".equals(syncRole.getSyncOpertaionType())){
				String url = Role_Base_Url + "/deleteGroupByUuid/" +syncRole.getRoleId();
				
				String result;
				try {
					result = HttpUtil.delete(url);
					JSONObject resJson = JSONObject.parseObject(result);
					if("1".equals(resJson.getString("result"))){
						this.synclogService.updateSyncResult(syncRole.getSyncSynclogId(), "success");
					}else{
						LOG.error("重新同步删除角色失败："+result);
					}
				} catch (IOException e) {
					LOG.error(e.getMessage());
				}
				
			}else if("update".equals(syncRole.getSyncOpertaionType())){
				//LOG.info("重新同步更新role到4A,日志id:"+syncRole.getSyncSynclogId());
				Map<String,String> paramMap = new HashMap<String,String>();
				JSONObject paramJson = new JSONObject();
				paramMap.put("uuid", syncRole.getRoleId());
				//paramJson.put("uuid", roleId);
				paramJson.put("name", syncRole.getRoleName());
				paramJson.put("groupCode", syncRole.getRoleRoleCode());
				paramJson.put("groupType", syncRole.getRoleType());
				
				paramMap.put("groupJson", paramJson.toJSONString());
				
				String url = Base_Url + "/updateGroupByUuid/" + syncRole.getRoleId();
				try {
					String result = HttpUtil.put(url, paramMap);
					JSONObject resJson = JSONObject.parseObject(result);
					if("1".equals(resJson.getString("result"))){
						this.synclogService.updateSyncResult(syncRole.getSyncSynclogId(), "success");
					}else{
						LOG.error("重新同步更新角色失败："+result);
					}
				} catch (Exception e) {
					LOG.error("重新同步更新角色到4A失败："+ e.getMessage());
				}
			
			}else{
				LOG.error(syncRole.getSyncOpertaionType()+" 操作类型不属于增、删、改。");
			}
		}
	}
	
	
	
}
